package com.vay.de.dang.online.util;

import android.app.Activity;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.util.Map;

public class WebViewUtil {

    private static OnLoadUrl mListener;
    private static Activity mActivity;

    public static void setLoadListener(OnLoadUrl listener, Activity activity) {
        mListener = listener;
        mActivity = activity;
    }

    public static void setting(WebView webView) {

        WebSettings webSettings = webView.getSettings();

        webView.setVerticalScrollBarEnabled(true);
        webView.setHorizontalScrollBarEnabled(false);

        webSettings.setJavaScriptEnabled(true);
        // 若加载的 html 里有JS 在执行动画等操作，会造成资源浪费（CPU、电量）
        // 在 onStop 和 onResume 里分别把 setJavaScriptEnabled() 给设置成 false 和 true 即可

        webSettings.setAllowFileAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        //缩放操作
        webSettings.setSupportZoom(false); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(false); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); // 支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); // 支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");// 设置编码格式

        // webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setTextZoom(100);

        webView.setWebViewClient(webClient);
    }

    public static void loadUrl(String url, WebView webView, Map<String, String> header) {

        // 设置参数
        setting(webView);

        // 长按事件
        webView.setOnLongClickListener(v -> true);

        // 加载url
        // Log.e("WebViewHelper", url);
        webView.loadUrl(url, header);
    }

    public static void loadData(String html, WebView webView) {

        // 设置参数
        setting(webView);

        // 长按事件
        webView.setOnLongClickListener(v -> true);

        // 加载url
        // Log.e("WebViewHelper", url);
        webView.loadData(html, null, "utf-8");
    }

    private static WebViewClient webClient = new WebViewClient() {

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            //AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
            //builder.setMessage(ResourceUtil.getString(R.string.label_ssl_failed));
            //builder.setPositiveButton(ResourceUtil.getString(R.string.bnt_confirm), (dialog, which) -> handler.proceed());
            //builder.setNegativeButton(ResourceUtil.getString(R.string.bnt_cancel), (dialog, which) -> handler.cancel());
            //AlertDialog dialog = builder.create();
            //dialog.show();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if (mListener != null) mListener.onStart();
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            String url = request.getUrl().toString();
            return super.shouldInterceptRequest(view, request);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (mListener != null) mListener.onEnd();
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
        }
    };

    public interface OnLoadUrl {

        void onStart();

        void onEnd();
    }
}
